var showFeature
var createFeatureLayer
var localDataFeatureLayers
var initFeatureLayer

require([
    "dojo/on",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",
    "esri/layers/GraphicsLayer",
    "esri/layers/FeatureLayer",
    "esri/graphic", "esri/Color",
    "esri/geometry/Point",
    "esri/geometry/Circle",
    "esri/layers/LabelClass", "esri/symbols/TextSymbol", "esri/symbols/Font",
    "esri/InfoTemplate",
    "dojo/domReady!"
], function (
    on, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol,
    GraphicsLayer, FeatureLayer, Graphic, Color, Point, Circle, LabelClass, TextSymbol, Font, InfoTemplate) {
    const pointColor = [238, 69, 0, 144]
    const pointOutlineColor = [238, 69, 0, 180]

    // //tabs切换时，触发搜索
    $(".featureListItem").click(function (e) {
        var a = $(this)[0].className.indexOf("active")
        if (a === -1) {
            $(this).addClass("active").siblings().removeClass("active");
            showFeature(this.innerText.trim())
        } else {
            $(this).removeClass("active");
            aroundGraphicLayer.clear()
            map.graphics.clear();
            map.infoWindow.hide();

            map.getLayer("医疗卫生").hide()
            map.getLayer("文化设施").hide()
            map.getLayer("公共服务").hide()
            map.getLayer("教育设施").hide()
            map.getLayer("宾馆酒店").hide()
            map.getLayer("红色资源").hide()

        }
    })

    showFeature = function (type) {
        type = type || "医疗卫生" //默认查询医疗卫生
        map.infoWindow.hide();
        aroundGraphicLayer.clear();
        circleGraphicLayer.clear();
        addressGraphicLayer.hide();

        map.getLayer("医疗卫生").hide()
        map.getLayer("文化设施").hide()
        map.getLayer("公共服务").hide()
        map.getLayer("教育设施").hide()
        map.getLayer("宾馆酒店").hide()
        map.getLayer("红色资源").hide()


        map.getLayer(type).show()
    }

    initFeatureLayer = function () {


        for (let key in aroundSearchData) {
            let aroundQueryList = []

            let featureGraphic = []
            // if (key === type) {
            const type = key
            const curTypeObj = aroundSearchData[key]
            for (let key in curTypeObj) {
                aroundQueryList.push(...curTypeObj[key])
            }

            for (let i = 0; i < aroundQueryList.length; i++) {
                var item = aroundQueryList[i];
                var sms = new PictureMarkerSymbol("img/icon/" + type + ".png", 20, 20).setOffset(0, 15);
                var pt = new Point(Number(item.x), Number(item.y), map.spatialReference);
                var attr = {};
                var infoCont = "<div class='infoCont'>";

                attr["名称"] = item.NAME;
                attr["类型"] = item.TYPE;
                attr["地址"] = item.ADDR;
                //   infoCont+="名称"+": "+ attr["名称"]+" <br/>";
                infoCont += "类型" + ": " + attr["类型"] + " <br/>";
                infoCont += "地址" + ": " + attr["地址"] + " <br/>";
                infoCont += "</div>"

                var infoTemplate = new InfoTemplate("<span style='font-weight:bold;color:\"#fff\"'>" + attr["名称"] + "</span>", infoCont);
                var graphic = new Graphic(pt, sms, attr, infoTemplate);

                // aroundGraphicLayer.add(graphic);
                featureGraphic.push(graphic)

            }

            createFeatureLayer(featureGraphic, type)
                .then(res => {
                    console.log(res)
                })
            // }
        }


    }



    createFeatureLayer = async function (features, type) {
        var dz = {
            //数据的基本属性
            "displayFieldName": "",
            "spatialReference": shanghaiSpatialRef,
        };

        if (features[0].geometry.hasOwnProperty("paths")) {
            dz.geometryType = "esriGeometryPolyline";
        } else if (features[0].geometry.hasOwnProperty("x")) {
            dz.geometryType = "esriGeometryPoint";
        } else if (features[0].geometry.hasOwnProperty("rings")) {
            dz.geometryType = "esriGeometryPolygon";
        }

        var attributes = features[0].attributes;
        var fields = [];
        var dzFeatures = [];

        var hasFID = false;

        for (var key in attributes) {
            if (key == "FID") {
                hasFID = true;
                var field = {
                    "name": key,
                    "type": "esriFieldTypeOID",
                    "alias": key,
                };
            } else {
                var field = {
                    "name": key,
                    "type": "esriFieldTypeString",
                    "alias": key,
                };
            }
            fields.push(field);
        }
        if (!hasFID) {
            var ofield = {
                "name": "FID",
                "type": "esriFieldTypeOID",
                "alias": "FID",
            };
            fields.push(ofield);
        }

        var count = 1;

        features.map((item) => {
            if (!hasFID) {
                item.attributes.FID = count;
                count++;
            }

            var dzFeature = {
                "attributes": item.attributes,
                "geometry": item.geometry,
            };

            dzFeatures.push(dzFeature);
        });

        dz.fields = fields;
        dz.features = dzFeatures;

        var featureSet = new esri.tasks.FeatureSet(dz);

        var featureCollection = {
            "layerDefinition": null,
            "featureSet": featureSet
        };

        if (features[0].geometry.hasOwnProperty("paths")) {
            featureCollection.layerDefinition = {
                "geometryType": dz.geometryType,
                "spatialReference": shanghaiSpatialRef,
                "drawingInfo": {
                    "renderer": {
                        "type": "simple",
                        "symbol": {
                            "color": lineColor,
                            "width": 2,
                            "type": "esriSLS",
                            "style": "esriSLSSolid"
                        }
                    }
                }
            };
        } else if (features[0].geometry.hasOwnProperty("x")) {
            featureCollection.layerDefinition = {
                "geometryType": dz.geometryType,
                "spatialReference": shanghaiSpatialRef,
                "drawingInfo": {
                    "renderer": {
                        "type": "simple",
                        "symbol": {
                            "url": "img/icon/" + type + ".png",
                            "height": 17,
                            "width": 17,
                            "type": "esriPMS",
                            "xoffset": 0,
                            "yoffset": 0,
                            // "yoffset": 15,
                        }
                        // {
                        //     "color": pointColor,
                        //     "size": 8,
                        //     "angle": 0,
                        //     "xoffset": 0,
                        //     "yoffset": 0,
                        //     "type": "esriSMS",
                        //     "style": "esriSMSCircle",
                        //     "outline": {
                        //         "color": pointOutlineColor,
                        //         "width": 1,
                        //         "type": "esriSLS",
                        //         "style": "esriSLSSolid"
                        //     }
                        // }
                    }
                }
            };
        } else if (features[0].geometry.hasOwnProperty("rings")) {
            featureCollection.layerDefinition = {
                "geometryType": dz.geometryType,
                "spatialReference": shanghaiSpatialRef,
                // "objectIdField": "ObjectID",
                "drawingInfo": {
                    "renderer": {
                        "type": "simple",
                        "symbol": {
                            'type': 'esriSFS',
                            'style': 'esriSFSSolid',
                            'color': polygonColor,
                            'outline': {
                                'type': 'esriSLS',
                                'style': 'esriSLSSolid',
                                'color': polygonOutlineColor,
                                'width': 1
                            }
                        }
                    }
                }
            }
        }

        featureCollection.layerDefinition.fields = fields;

        // var infoTemplate = features[0].infoTemplate;
        var infoTemplate = createInfoTemplate(attributes);;


        var layerId = type;

        const layer = await initlocalDataFeatureLayer(featureCollection, layerId, infoTemplate, features)

        // console.log("layer加载完成")
        return layer
    }

    function createInfoTemplate(attributes) {
        var infoCont = "<div class='infoCont'>";
        infoCont += "类型" + ": ${类型}<br/>";
        infoCont += "地址" + ": ${地址}<br/>";
        infoCont += "</div>"
        var infoTemplate = new InfoTemplate("<span style='font-weight:bold;color:#fff'>${名称}</span>", infoCont);
       
        return infoTemplate;
    }

    function initlocalDataFeatureLayer(featureCollection, layerId, infoTemplate, features) {
        const promise = new Promise(resolve => {
            var statesLabel = new TextSymbol().setColor(new Color("#fff")).setHaloSize(0.5).setHaloColor(new Color("#000")).setOffset(0,4);
            statesLabel.font.setSize("11pt");
            statesLabel.font.setWeight(600);
            var labelClass = new LabelClass({
                "labelExpressionInfo": {
                    "value": "{名称}"
                },
                "labelPlacement": "above-center",
            });
            labelClass.symbol = statesLabel;
            labelClass.minScale = 50000;
            // labelClass.maxScale = 10000;

            //featureCollection中的featureSet被限制50000个
            var localDataFeatureLayer = new FeatureLayer(featureCollection, {
                id: layerId,
                spatialReference: shanghaiSpatialRef,
                infoTemplate: infoTemplate,
                // visible: true,
                visible: false,
                // labelingInfo: [{
                //     "labelExpressionInfo": {
                //         "value": "{名称}"
                //     },
                //     "useCodedValues": false, //parameters used when attribute field has domain values,
                //     "labelPlacement": "above-right",
                //     // "symbol": {
                //     //     font: new Font("12", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_BOLD, "微软雅黑"),
                //     //     color: new Color("#fff")
                //     // }, //TextSymbol used for labeling
                //     // "minScale": 0, //specified scale range where labels are visible
                //     // "maxScale": 5000,
                //     //fieldInfos structure describes attribute field formatting
                //     // "fieldInfos": [
                //     //   { fieldName: "created_date", format: { dateFormat: "shortDate"} }, //date/time formatting 
                //     //   { fieldName: "last_edited_date", format: { dateFormat: "longDate"} },  //date/time formatting
                //     //   { fieldName: "eventtype", format: { places: 6, digitSeparator: true } } //numeric formatting
                //     // ],
                // }]

            });

            localDataFeatureLayer.setLabelingInfo([labelClass]);

            localDataFeatureLayer.on("load", function (e) {
                //匹配结果构造的featureLayer最大存储50000个，大于50000的自行添加
                if (features.length > 50000) {
                    for (let i = 50000; i < features.length; i++) {
                        let graphic = features[i];
                        graphic.symbol = null;
                        graphic.infoTemplate = null;

                        localDataFeatureLayer.graphics.push(features[i]);
                    }
                }
                // localDataFeatureLayers.push(localDataFeatureLayer);

                // map.addLayer(localDataFeatureLayers[localDataFeatureLayers.length - 1]);
                map.addLayer(localDataFeatureLayer);

                //给每个FeatureLayer添加鼠标移入事件
                localDataFeatureLayer.on("mouse-over", function (evt) {
                    // 鼠标进入FeatureLayer的要素时，鼠标变手型提醒
                    map.setMapCursor("pointer");
                });
                localDataFeatureLayer.on("mouse-out", function (evt) {
                    map.setMapCursor("default");
                });

                resolve(localDataFeatureLayer);
            });


        })

        return promise;
    }
})